package com.bjsxt.shop.common.util;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.NumberFormat;

/**
 * 浮点数计算的工具类
 * 
 * @author root
 *
 */
public class DoubleUtil
{
	/**
	 * 两个浮点数相加
	 * @param a
	 * @param b
	 * @return
	 */
	public BigDecimal add(double a , double b)
	{
		BigDecimal bigA = new BigDecimal(a);
		BigDecimal bigB = new BigDecimal(b);
		return bigA.add(bigB) ; 
	}
	
	/**
	 * 两个浮点数相减
	 * @param a
	 * @param b
	 * @return
	 */
	public BigDecimal sub(double a , double b)
	{
		BigDecimal bigA = new BigDecimal(a);
		BigDecimal bigB = new BigDecimal(b);
		return bigA.subtract(bigB) ; 
	}
	
	/**
	 * 两个浮点数相乘
	 * @param a
	 * @param b
	 * @return
	 */
	public BigDecimal multiply(double a , double b)
	{
		BigDecimal bigA = new BigDecimal(a);
		BigDecimal bigB = new BigDecimal(b);
		return bigA.multiply(bigB) ; 
	}
	
	/**
	 * 两个浮点数相除
	 * @param a
	 * @param b
	 * @return
	 */
	public BigDecimal divide(double a , double b)
	{
		BigDecimal bigA = new BigDecimal(a);
		BigDecimal bigB = new BigDecimal(b);
		return bigA.divide(bigB) ; 
	}
	
	/**
	 * 保留小数点以后几位
	 * 默认四舍五入
	 * 
	 * @param flag 0:四舍五入,1:进1法,2:舍去法
	 * @return
	 */
	public double scale(double num,int wei,String flag)
	{
		RoundingMode mode = RoundingMode.HALF_UP ; 
		if("1".equalsIgnoreCase(flag))
		{
			mode = RoundingMode.CEILING ; 
		}else if("2".equalsIgnoreCase(flag))
		{
			mode = RoundingMode.DOWN ; 
		}
		BigDecimal bigA = new BigDecimal(num);
		bigA = bigA.setScale(wei,mode);
		return bigA.doubleValue() ;
	}
	
	public static void main(String[] args)
	{
		double a = 100002.1 ; 
		double b = 88881.2 ; 
		double d = a - b;
		System.out.println(d);
		/* 如何取小数点以后的两位? */
		NumberFormat format = new DecimalFormat("###,000.0");
		String res = format.format(d);
		System.out.println("res===========" + res);
		
		BigDecimal bigA = new BigDecimal(a);
		BigDecimal bigB = new BigDecimal(b);
		bigA = bigA.subtract(bigB);
		System.out.println(bigA);
		bigA = bigA.setScale(14,RoundingMode.HALF_UP);
		System.out.println(bigA.doubleValue());
	}
}
